import { Logger } from '@nestjs/common';
import { 
  ApiAdapter, 
  ApiProvider, 
  TargetProvider, 
  GenericRequest, 
  GenericResponse, 
  HealthStatus,
  TokenManager
} from '../interfaces/api-adapter.interface';

/**
 * 适配器基础抽象类
 * 为所有适配器提供通用功能和默认实现
 */
export abstract class BaseAdapter implements ApiAdapter {
  protected readonly logger: Logger;

  constructor(
    public readonly provider: ApiProvider,
    public readonly target: TargetProvider
  ) {
    this.logger = new Logger(`${provider.toUpperCase()}To${target.toUpperCase()}Adapter`);
  }

  // 抽象方法 - 子类必须实现
  abstract convertToGeneric(sourceRequest: any): Promise<GenericRequest>;
  abstract convertFromGeneric(genericRequest: GenericRequest): Promise<any>;
  abstract parseTargetResponse(targetResponse: any, originalRequest?: any): Promise<GenericResponse>;
  abstract convertToSourceResponse(genericResponse: GenericResponse, originalRequest?: any): Promise<any>;
  abstract getRequestHeaders(config: any): Promise<Record<string, string>>;
  abstract getTargetEndpoint(operation: string): string;

  /**
   * 默认请求验证实现
   */
  async validateRequest(request: any): Promise<boolean> {
    if (!request) {
      this.logger.warn('Request is null or undefined');
      return false;
    }

    // 基础验证 - 检查必需字段
    const requiredFields = this.getRequiredFields();
    for (const field of requiredFields) {
      if (!this.hasNestedProperty(request, field)) {
        this.logger.warn(`Missing required field: ${field}`);
        return false;
      }
    }

    return true;
  }

  /**
   * 默认健康检查实现
   */
  async checkHealth(): Promise<HealthStatus> {
    try {
      // 基础健康检查 - 可以被子类覆盖
      const tokenManager = this.getTokenManager?.();
      const hasValidToken = tokenManager ? tokenManager.isTokenValid() : true;

      return {
        status: hasValidToken ? 'healthy' : 'degraded',
        provider: this.provider,
        target: this.target,
        details: {
          hasTokenManager: !!tokenManager,
          tokenValid: hasValidToken
        },
        lastCheck: new Date()
      };
    } catch (error) {
      this.logger.error(`Health check failed: ${error.message}`);
      return {
        status: 'unhealthy',
        provider: this.provider,
        target: this.target,
        details: {
          error: error.message
        },
        lastCheck: new Date()
      };
    }
  }

  /**
   * 获取 Token 管理器（可选实现）
   */
  getTokenManager?(): TokenManager;

  /**
   * 获取必需字段列表 - 子类可以覆盖
   */
  protected getRequiredFields(): string[] {
    return ['model', 'messages'];
  }

  /**
   * 检查嵌套属性是否存在
   */
  protected hasNestedProperty(obj: any, path: string): boolean {
    const keys = path.split('.');
    let current = obj;
    
    for (const key of keys) {
      if (current == null || typeof current !== 'object' || !(key in current)) {
        return false;
      }
      current = current[key];
    }
    
    return current !== undefined && current !== null;
  }

  /**
   * 深度复制对象
   */
  protected deepClone<T>(obj: T): T {
    return JSON.parse(JSON.stringify(obj));
  }

  /**
   * 生成请求 ID
   */
  protected generateRequestId(): string {
    return `${this.provider}_${this.target}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  }

  /**
   * 标准化模型名称
   */
  protected normalizeModelName(model: string): string {
    return model.toLowerCase().trim();
  }

  /**
   * 提取文本内容（从各种内容格式中）
   */
  protected extractTextContent(content: any): string {
    if (typeof content === 'string') {
      return content;
    }
    
    if (Array.isArray(content)) {
      return content
        .filter(block => block.type === 'text')
        .map(block => block.text || '')
        .join('\n');
    }
    
    return '';
  }

  /**
   * 估算 token 数量（简单实现）
   */
  protected estimateTokenCount(text: string): number {
    if (!text) return 0;
    
    // 简单估算：英文约4字符=1token，中文约1.5字符=1token
    const englishChars = (text.match(/[a-zA-Z0-9\s]/g) || []).length;
    const chineseChars = (text.match(/[\u4e00-\u9fff]/g) || []).length;
    const otherChars = text.length - englishChars - chineseChars;
    
    return Math.ceil(
      englishChars / 4 + 
      chineseChars / 1.5 + 
      otherChars / 3
    );
  }

  /**
   * 映射停止原因
   */
  protected mapStopReason(reason: string): string {
    const stopReasonMap: Record<string, string> = {
      'stop': 'end_turn',
      'length': 'max_tokens',
      'tool_calls': 'tool_use',
      'content_filter': 'refusal',
      'function_call': 'tool_use'
    };
    
    return stopReasonMap[reason] || 'end_turn';
  }

  /**
   * 创建错误响应
   */
  protected createErrorResponse(message: string, type: string = 'api_error'): any {
    return {
      type: 'error',
      error: {
        type,
        message
      }
    };
  }

  /**
   * 日志记录辅助方法
   */
  protected logConversion(from: string, to: string, details?: any): void {
    this.logger.debug(`Converting ${from} -> ${to}`, details);
  }

  /**
   * 验证配置完整性
   */
  protected validateConfig(config: any, requiredKeys: string[]): boolean {
    for (const key of requiredKeys) {
      if (!config || !config[key]) {
        this.logger.error(`Missing required config key: ${key}`);
        return false;
      }
    }
    return true;
  }

  /**
   * 安全地访问嵌套对象属性
   */
  protected safeGet(obj: any, path: string, defaultValue: any = null): any {
    try {
      const keys = path.split('.');
      let current = obj;
      
      for (const key of keys) {
        if (current == null || typeof current !== 'object' || !(key in current)) {
          return defaultValue;
        }
        current = current[key];
      }
      
      return current !== undefined ? current : defaultValue;
    } catch {
      return defaultValue;
    }
  }
}